<template>
  <div class="login">
    <div class="login-form">
      <h2>登录</h2>

      <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="70px" v-if="!codeLog">

        <el-form-item label="手机号" prop="email">
          <el-input prefix-icon="Cellphone" placeholder="请填写手机号" maxlength="32" v-model="loginForm.email" ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input prefix-icon="Lock" placeholder="请填写 6-18 位密码" type="password" maxlength="18" v-model="loginForm.password" show-password></el-input>
        </el-form-item>

        <div class="b"><span @click="codeLog = true">验证码登录</span></div>

        <el-form-item class="btn-r" label-width="0px">
          <el-button type="danger" icon="Promotion" :loading="loading" @click="submitForm('loginForm')">登 录</el-button>
        </el-form-item>

        <el-form-item class="btn-l" label-width="0px">
          <router-link to="/register">
             <el-button type="success" icon="Back">注 册</el-button></router-link>
        </el-form-item>
      </el-form>

      <el-form :model="codeLoginForm" :rules="rules" ref="codeLoginForm" label-width="70px" v-if="codeLog">

        <el-form-item label="手机号" prop="email">
          <el-input prefix-icon="Cellphone" placeholder="请填写手机号" maxlength="32" v-model="codeLoginForm.email" ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input prefix-icon="Key" placeholder="请填写6位数字验证码" type="number" maxlength="6" v-model="codeLoginForm.phoneCode">
            <!--          <el-button slot="append" @click="sendEmailCode()" :disabled="disabled">{{ msg }}</el-button>-->
            <template #append>
              <el-button @click="sendPhoneCode()" :disabled="disabled">{{msg}}</el-button>
            </template>
          </el-input>
        </el-form-item>

        <div class="b"><span @click="codeLog=false">密码登录</span></div>

        <el-form-item class="btn-r" label-width="0px">
          <el-button type="danger" icon="Promotion" :loading="loading" @click="submitForm2('codeLoginForm')">登 录</el-button>
        </el-form-item>

        <el-form-item class="btn-l" label-width="0px">
          <router-link to="/register">
            <el-button type="success" icon="Back">注 册</el-button></router-link>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>
<script>

import { Message, Lock,Back,Promotion,Cellphone } from "@element-plus/icons-vue";
export default {
  name: "Login",
  setup(){
    return{
      Message,
      Lock,
      Back,
      Promotion,
      Cellphone
    }
  },
  data() {
    return {
      loginForm: {
        email:"",
        password: '',
      },
      codeLog: false,
      codeLoginForm: {
        email: '',
        phoneCode: '',
      },
      receive:'',
      disabled: false,
      msg: '点击获取验证码',
      count: 60,
      timer: 0,
      // 按钮加载
      loading: false,
      rules: {
        email: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        phoneCode: [
          { required: true, message: '请输入短信验证码', trigger: 'blur' },
          { min: 6, max: 6, message: '长度为6个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {

    submitForm2(formName){
      this.$refs[formName].validate((valide)=>{
        if(valide){
          const _this = this;
          if(_this.receive!==_this.codeLoginForm.phoneCode){
            console.log("this.receive:"+this.receive)
            console.log("formName.phone:"+_this.codeLoginForm.phoneCode)
            this.$message({
              message: '验证码错误！',
              type: 'fail'
            })
          }else{
            _this.$axios({
                url:"/codeLogin",
                data:
            {
              email:_this.codeLoginForm.email
            },
              method:"post"
            }).then(res=>{
              const jwt = res.headers['authorization']; // 将 jwt 放入 localstore - 此参数要分享给所有组件
              const userInfo = res.data
              console.log(res.data)
              _this.$store.commit("SET_TOKEN", jwt); // 调用我们书写的方法，填写全局信息
              _this.$store.commit("SET_USERINFO", userInfo);
              //获取token和getUser
              // console.log(_this.$store.getters.getToken)
              // console.log(_this.$store.getters.getUser)
              //跳转租户管理页面 - tenantManage
              _this.$router.push("/survey")
            })
          }
        }else{
          console.log("error")
          return false
        }
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this;//获取整个vue的this,将 this 保存起来，是请求的 this
          _this.$axios.post("/login", _this.loginForm).then(res => {
          if(res.data.code=200) {
            const jwt = res.headers['authorization']; // 将 jwt 放入 localstore - 此参数要分享给所有组件
            const userInfo = res.data
            console.log(res)
            //存储(共享)全局变量jwt和userInfo —— 将 user 赋值给全局
            _this.$store.commit("SET_TOKEN", jwt); // 调用我们书写的方法，填写全局信息
            _this.$store.commit("SET_USERINFO", userInfo);
            //获取token和getUser
            // console.log(_this.$store.getters.getToken)
            // console.log(_this.$store.getters.getUser)
            //跳转租户管理页面 - tenantManage
            _this.$router.push("/survey")
          }else if(res.data.code=400){
            this.$message({
              message: '密码错误！',
              type: 'fail'
            })
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    sendPhoneCode() {
      this.$refs.codeLoginForm.validateField('email', result => {
        //  if(!result) {

        // 按钮倒计时
        this.disabled = true;
        this.msg = this.count-- + 's后重新获取';
        this.timer = setInterval(() => {
          this.msg = this.count-- + 's后重新获取';
          if (this.count < 0) {
            this.msg = '点击获取验证码';
            this.count = 60;
            this.disabled = false;
            clearInterval(this.timer);
          }
        }, 1000);
        // 发送验证码请求
        const _this=this;
        _this.$axios.post('/sendPhoneCode', {
          phoneNum:_this.codeLoginForm.email
        }).then(res=>res.data).then(res=>{
          if(res){
            console.log("data:"+res)
            console.log("data.receive:"+res.data.receive)
            _this.receive=res.data.receive;
            _this.$notify({
              title: '短信验证码已发送',
              message: '验证码有效时长5分钟, 失效请重新发送',
              type: 'success',
              duration: 10 * 1000
            })
          }
        })
      });
    },
  }
}
</script>

<style>
.login {
  background-color: azure;
  height: 100%;

  display: flex;
  justify-content: center;
  align-items: center;
  background: url('../assets/login.jpg') fixed no-repeat;
  background-size: 100% 100%;
}

.login-form {
  height: 350px;
  width: 600px;
  box-sizing: border-box;
  background-color: #fff;
  opacity: 0.8;
  padding: 20px 50px;
}

.login input::-webkit-outer-spin-button,
.login input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

.login input[type='number'] {
  -moz-appearance: textfield;
}

.btn-r {
  width: 100px;
  float: right;
}

.btn-l {
  width: 100px;
  float: left;
}

.b span {
  font-size: 12px;
  cursor: pointer;
  display: inline-block;
  margin-top: 5px;
}

.el-dialog {
  padding: 0px 50px;
}
</style>